package com.ruoyi.excel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.ruoyi.common.convert.ExcelBigNumberConvert;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.excel.CellMergeStrategy;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.excel.domain.AsyncImportExportTask;
import com.ruoyi.excel.service.AsyncTaskCommonService;
import com.ruoyi.excel.service.IAsyncImportExportTaskService;
import com.ruoyi.system.domain.vo.SysUserExportVo;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author fjw
 * @date 2023-06-27
 */
@Component("D-A-01")
@Slf4j
public class ExportUserInfoData implements AsyncTaskCommonService {

    @Value("${temp.file.path}")
    private String baseTempFilePath;
    @Autowired
    private IAsyncImportExportTaskService asyncImportExportTaskService;
    @Override
    public void invoke(AsyncImportExportTask asyncImportExportTask) {
        log.info(Thread.currentThread().getName() + "导出历史呼叫记录。。。");
        String className = asyncImportExportTask.getJavaType();
        String jsonString = asyncImportExportTask.getListData();
        String filePath = null;
        try {
            Class aClass = Class.forName(className);
            List list = JsonUtils.parseObject(jsonString, List.class);
            List<?> data = BeanUtil.copyToList(list, Class.forName(className));
            filePath = baseTempFilePath + UUID.randomUUID() + ".csv";
            File file = new File(filePath);
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream os= new FileOutputStream(file);
            ExcelWriterSheetBuilder builder = EasyExcel.write(os,aClass)
                .autoCloseStream(true)
                // 自动适配
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                // 大数值自动转换 防止失真
                .registerConverter(new ExcelBigNumberConvert())
                .sheet("异步代码测试");
            builder.doWrite(data);
        } catch (Exception e) {
            log.error("invoke FileWriter error:", e);
            asyncImportExportTask.setResult("任务失败");
            asyncImportExportTask.setFinishTime(new Date());
            asyncImportExportTask.setTaskStatus(4);
            asyncImportExportTaskService.saveOrUpdate(asyncImportExportTask);
            log.info(Thread.currentThread().getName() + "导出任务失败！！！！！！！！！！！！");
        }
        String tag = filePath.substring(0);
        asyncImportExportTask.setResult("任务成功");
        asyncImportExportTask.setFinishTime(new Date());
        asyncImportExportTask.setTaskStatus(3);
        asyncImportExportTask.setTag(tag);
        asyncImportExportTaskService.saveOrUpdate(asyncImportExportTask);
        log.info(Thread.currentThread().getName() + "导出任务完成！！！！！！！！！！！！");
    }
}
